import React, { useContext, useEffect, useState } from "react";

// 创建Context
const UseContext = React.createContext();
//解构赋值
const { Provider, Consumer } = UseContext;
export default function useContextFunction() {
    const initName = 'Mike';
    const [name, setName] = useState(initName);
    //5000ms后修改name
    useEffect(() => {
        setTimeout(() => setName('DQ'), 1000);
    }, [])
    //注销函数
    const logout = () => {
        setName('');
    }
    return (<>
        <Provider value={{
            name: name,
            // 注销函数
            logout
        }}>
            {/* 任意的消费者 */}
            <Consumer>
                {value => <a>{value.name}</a>}
            </Consumer>
            <Children />
        </Provider>
    </>
    );
}

// 写法
function Children() {
    const {name,logout}= useContext(UseContext);
    return (
    <>
        <h3>Children</h3>
        <button onClick={logout}>注销</button>
        <a>{name}</a>
        </>
    )
}